#include "Camera.h"
#include "Timer.h"
#include "PlayState.h"
#include "Catapult.h"
#include "Ball.h"
#include "RadDegConvert.h"

Camera::Camera()
{
	TheEventPoller::Instance()->AddHandler(this);
	m_pos = Vec3f(0, 50, 400);
	m_dest = Vec3f(0, 15, 0);
	m_aimingDistance = 400;
}

Camera::~Camera()
{
	TheEventPoller::Instance()->RemoveHandler(this);
}

void Camera::Update()
{
	float elapsedTime = TheTimer::Instance()->GetDT();
	float rotateSpeed = 20;

	Catapult* cata = ThePlayState::Instance()->GetCatapultAddress();

	if(cata->GetIsAiming() || cata->GetIsFiring())
	{
		m_firingAngleXDiff = 0;
		float yRotRad = -DegToRad(cata->GetYRotation()) + 1.57f;
		m_pos = Vec3f((m_aimingDistance * cos(yRotRad)) , 50, m_aimingDistance * sin(yRotRad));
		m_dest = Vec3f(0, 15, 0);
	}
	if(cata->GetIsWaiting())
	{
		if(m_firingAngleXDiff < 0.8f)
		{
			m_firingAngleXDiff += 0.1f * elapsedTime;
		}
		Ball* b = ThePlayState::Instance()->GetBall();
		btVector3 ballPos = b->GetRigidBody()->getWorldTransform().getOrigin();
		float yRotRad = -DegToRad(cata->GetYRotation()) + 1.57f;
		m_pos = Vec3f(ballPos.x() + (m_aimingDistance * cos(yRotRad + m_firingAngleXDiff)) , ballPos.y() + 50, ballPos.z() + m_aimingDistance * sin(yRotRad));
		m_dest = m_dest = Vec3f(ballPos.x(), ballPos.y() - 20, ballPos.z());
	}

	if(m_movingUp)
	{
		m_pos.Y += rotateSpeed * elapsedTime;
	}
	if(m_movingDown)
	{
		m_pos.Y -= rotateSpeed * elapsedTime;
	}
	if(m_movingLeft)
	{
		m_pos.X -= rotateSpeed * elapsedTime * 2;
	}
	if(m_movingRight)
	{
		m_pos.X += rotateSpeed * elapsedTime * 2;
	}
	if(m_movingIn)
	{
		m_pos.Z -= rotateSpeed * elapsedTime;
	}
	if(m_movingOut)
	{
		m_pos.Z += rotateSpeed * elapsedTime;
	}
}

void Camera::OnKeyboardEvent(const SDL_KeyboardEvent& t)
{
	if(t.keysym.sym == SDLK_UP && t.state == SDL_PRESSED)
	{
		m_movingUp = true;
	}
	else
	{
		m_movingUp = false;
	}

	if(t.keysym.sym == SDLK_DOWN && t.state == SDL_PRESSED)
	{
		m_movingDown = true;
	}
	else
	{
		m_movingDown = false;
	}
	if(t.keysym.sym == SDLK_RIGHT && t.state == SDL_PRESSED)
	{
		m_movingRight = true;
	}
	else 
	{
		m_movingRight = false;
	}
	if(t.keysym.sym == SDLK_LEFT && t.state == SDL_PRESSED)
	{
		m_movingLeft = true;
	}
	else 
	{
		m_movingLeft = false;
	}
	if(t.keysym.sym == SDLK_q && t.state == SDL_PRESSED)
	{
		m_movingOut = true;
	}
	else
	{
		m_movingOut = false;
	}
	if(t.keysym.sym == SDLK_e && t.state == SDL_PRESSED)
	{
		m_movingIn = true;
	}
	else
	{
		m_movingIn = false;
	}
}